package com.cyou.qb.face.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.cyou.fz173.util.JacksonUtil;
import com.cyou.nad.utils.MD5;
import com.cyou.qb.face.dao.OutServiceFailDAO;
import com.cyou.qb.face.entity.AddressInfo;
import com.cyou.qb.face.entity.Face173AccessLog;
import com.cyou.qb.face.entity.OutService;
import com.cyou.qb.face.entity.UserContact;
import com.cyou.qb.face.entity.UserInfo;
import com.cyou.qb.face.entity.trans.Account;
import com.cyou.qb.face.entity.trans.Completion;
import com.cyou.qb.face.entity.trans.Experience;
import com.cyou.qb.face.entity.trans.MemberInfo;
import com.cyou.qb.face.entity.trans.ReplyCheck;
import com.cyou.qb.face.entity.trans.ReplyInfoCheck;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.log.IOutServiceLog;
import com.cyou.qb.face.service.PassportCheckService;
import com.cyou.qb.face.util.contants.FaceContants;
import com.cyou.qb.face.util.converter.FaceHttpUtil;
import com.cyou.qb.face.util.converter.FaceStringUtil;

@Component("PassportCheckServiceImpl")
public class PassportCheckServiceImpl extends BaseFaceServiceimpl implements
		PassportCheckService {

	@Value("${face.USERURL}")
	private String facePHPURL;
	@Value("${face.SNSURL}")
	private String faceSNSURL;
	@Value("${face.memberURL}")
	private String memberURL;
	@Value("${face.infoCompletionURL}")
	private String infoCompletionURL;
	@Value("${face.addJifen}")
	private String addJifen;
	@Value("${face.getJifen}")
	private String getJifen;
	Logger logger = Logger.getLogger(PassportCheckServiceImpl.class);

	@Autowired
	private IOutServiceLog outServiceLog;

	/**
	 * 回写用户地址信息 调用Member.updateMemberContact接口
	 */
	@Override
	public boolean updateAddress(int uid, AddressInfo address, String passport) 
			throws QbGetDataException {
		/**
		 * 记录切面日志
		 */
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		/**
		 * 装填需要的数据
		 */
		UserContact userContact = this.getContact(uid, passport);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("apikey", FaceContants.API_KEY);
		map.put("method", "Member.updateMemberContact");
		map.put("ver", FaceContants.API_VERSION);
		map.put("uid", uid);
		map.put("province", userContact.getProvince());
		map.put("city", userContact.getCity());
		map.put("email", userContact.getEmail());
		map.put("msn", userContact.getMSN());
		map.put("address", address.getDetailedAddress());
		map.put("phone", address.getMobilephone());
		map.put("qq", userContact.getQqNum());
		/**
		 * 拼接请求URL
		 */
		String url = FaceStringUtil.createURLString(faceSNSURL, map);

		accessLog.setCallServiceParam(url);
		String resultJson = null;
		boolean flag = false;
		/**
		 * 发出http get请求
		 */
		try {
			resultJson = FaceHttpUtil.doRequest(url, null, null,
					FaceContants.UTF8_ENCODE).trim();
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			/**
			 * 处理返回结果
			 */
			@SuppressWarnings("rawtypes")
			ReplyInfoCheck rfc = JacksonUtil.toObject(resultJson,ReplyInfoCheck.class);
			if (rfc != null) {
				if (rfc.getCode() == ReplyInfoCheck.CODE_OK) {
					flag = true;
				}
			}
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			/**
			 * 记录错误日志写入数据库库
			 */
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getMemberInfo throw QbGetDataException"+ e.getMessage(),e);
			throw new QbGetDataException("getMemberInfo throw Exception"+ e.getMessage(),e);

		}
	}

	@Override
	/**
	 * 为用户加经验
	 */
	public boolean plusExperience(int uid, String memo, int experienceValue,
			String userName) throws QbGetDataException {
		String url="";
		String jsonURL = null;
		try {
			/**
			 * 记录切面日志
			 */
			Face173AccessLog accessLog = getAccessLog();
			accessLog.setCallService(this.getClass().getName());
			/**
			 * 装填数据
			 */
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userid", uid);
			map.put("jifen", experienceValue);
			map.put("action", "add");
			map.put("channel", FaceContants.QB_CHANNEL);
			map.put("chk", MD5.encode(uid + "" + FaceContants.MD5_KEY));
			/**
			 * 拼接请求URL
			 */
			url = FaceStringUtil.createURLString(facePHPURL + addJifen, map);
			accessLog.setCallServiceParam(url);
			/**
			 * 发出http get请求
			 */
			jsonURL = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(jsonURL);
			/**
			 * 处理返回结果是XML的数据
			 */
			Document doc;
			Element flagEle = null;
			doc = DocumentHelper.parseText(jsonURL);
			Element root = doc.getRootElement();
			flagEle = root.element("flag");
			return flagEle.getData().equals("1") ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
			/**
			 * 记录错误日志写入数据库库
			 */
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_EXPERIENCE);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(jsonURL);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("plusExperience throw Exception" + e.getMessage(),e);
			throw new QbGetDataException("plusExperience throw Exception"+ e.getMessage(),e);

		}
		
	}

	/**
	 * 获取用户站内等级
	 */
	@Override
	public int getUserLv(int uid, String passport) throws QbGetDataException {

		String lvString = this.getUserLv("getUserLv", uid, passport);
		Experience exper = JacksonUtil.toObject(lvString, Experience.class);
		String lv = exper.getJifen();
		String lvi = lv.substring(lv.indexOf("|") + 1, lv.lastIndexOf("|"));
		return Integer.parseInt(lvi);
	}

	/**
	 * 获取用户信息完整度
	 * 
	 * @throws QbGetDataException
	 */
	@Override
	public int getUserInfoCompletion(int uid) throws QbGetDataException {

		String completionString = this.getInfoCompletion("getInfoCompletion",
				uid, FaceContants.INFOMARK_BASEINFO);
		Completion completion = JacksonUtil.toObject(completionString,
				Completion.class);

		return completion.getBaseInfoCompletion();
	}

	/**
	 * 获取联系方式完整度
	 * 
	 * @throws QbGetDataException
	 */
	@Override
	public int getContactCompletion(int uid) throws QbGetDataException {

		String completionString = this.getInfoCompletion("getInfoCompletion",
				uid, FaceContants.INFOMARK_BASEINFO);
		Completion completion = JacksonUtil.toObject(completionString,
				Completion.class);

		return completion.getContactInfoCompletion();
	}

	@Override
	/**
	 * 使玩家关注活动所对应的游戏
	 */
	public boolean addGameFocus(String gamecode, int uid)
			throws QbGetDataException {
		boolean flag = false;

		String transport = this.isFocus("Game.addGameFocus", uid, gamecode);
		ReplyCheck reply = null;
		reply = JacksonUtil.toObject(transport, ReplyCheck.class);

		if (reply.getCode() == 0) {
			flag = true;
		}
		return flag;
	}

	@Override
	/**
	 * 判断玩家是否对游戏有关注
	 */
	public boolean isFocus(String gamecode, int uid) throws QbGetDataException {
		boolean flag = false;

		String transport = this.isFocus("Game.isFocus", uid, gamecode);

		ReplyCheck reply = JacksonUtil.toObject(transport, ReplyCheck.class);
		System.out.println(reply);
		if (reply.getCode() == 1) {
			flag = true;
		}
		return flag;
	}

	@Override
	/**
	 * 获取用户信息
	 */
	public UserInfo getUserInfo(int uid) throws QbGetDataException {

		String completionString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_ACCOUNT_BASE);
		MemberInfo memberInfo = JacksonUtil.toObject(completionString, MemberInfo.class);
		
		UserInfo userInfo = new UserInfo();
		if(memberInfo != null && memberInfo.getBaseInfo() != null && memberInfo.getAccount() != null){
			userInfo.setBirthday(memberInfo.getBaseInfo().getBirthday());
			userInfo.setConstellation(memberInfo.getBaseInfo().getConstellation());
			userInfo.setName(memberInfo.getBaseInfo().getName());
			userInfo.setPlayStage(memberInfo.getBaseInfo().getGameStage());
			userInfo.setSex(memberInfo.getBaseInfo().getSex());
			userInfo.setNickname(memberInfo.getAccount().getNickname());
			userInfo.setUserPassport(memberInfo.getAccount().getAccId());
		}
		return userInfo;
	}

	@Override
	/**
	 * 获取用户昵称
	 */
	public String getUserNickname(int uid) throws QbGetDataException {

		MemberInfo memberInfo = null;
		String accountString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_DEFAULT_ACCOUNT);
		String nickname = "";
		memberInfo = JacksonUtil.toObject(accountString, MemberInfo.class);

		if (memberInfo != null && memberInfo.getAccount() != null) {
			nickname = memberInfo.getAccount().getNickname();
		} else {
			throw new QbGetDataException();
		}
		return nickname;
	}

	/**
	 * 获取用户联系地址
	 */
	@Override
	public AddressInfo getAddressInfo(int uid, String passport)
			throws QbGetDataException {
		AddressInfo address = new AddressInfo();

		String contactString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_CONTACT);

		MemberInfo memberInfo = JacksonUtil.toObject(contactString,
				MemberInfo.class);
		
		String bascString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_BASEINFO);

		MemberInfo baseInfo = JacksonUtil
				.toObject(bascString, MemberInfo.class);

		if(memberInfo != null && memberInfo.getContact() != null){
			
			address.setCity(memberInfo.getContact().getCity());
			address.setDetailedAddress(memberInfo.getContact().getAddress());
			address.setMobilephone(memberInfo.getContact().getPhone());
			address.setProvince(memberInfo.getContact().getProvince());
			address.setQqNum(memberInfo.getContact().getQq());
			address.setUserPassport(passport);
			
			if(baseInfo != null && baseInfo.getBaseInfo() != null){
				address.setUserTrueName(baseInfo.getBaseInfo().getName());
			}
		}

		return address;
	}

	/**
	 * 获取用户联系方式
	 */
	@Override
	public UserContact getContact(int uid, String passport)
			throws QbGetDataException {
		UserContact userContact = new UserContact();
		String contactString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_CONTACT);

		MemberInfo memberInfo = JacksonUtil.toObject(contactString,
				MemberInfo.class);

		String bascString = this.getMemberInfo("getMemberInfo", uid,
				FaceContants.INFOMARK_BASEINFO);

		MemberInfo baseInfo = JacksonUtil
				.toObject(bascString, MemberInfo.class);

		if(memberInfo != null && memberInfo.getContact() != null){
			userContact.setCity(memberInfo.getContact().getCity());
			userContact.setDetailedAddress(memberInfo.getContact().getAddress());
			userContact.setMobilephone(memberInfo.getContact().getPhone());
			userContact.setProvince(memberInfo.getContact().getProvince());
			userContact.setQqNum(memberInfo.getContact().getQq());
			userContact.setEmail(memberInfo.getContact().getEmail());
			userContact.setMSN(memberInfo.getContact().getMsn());
			userContact.setUserPassport(passport);
			if(baseInfo != null && baseInfo.getBaseInfo() != null){
				userContact.setUserTrueName(baseInfo.getBaseInfo().getName());
			}
		}

		return userContact;
	}

	/**
	 * 调用接口获取member信息
	 * 
	 * @param method
	 * @param uid
	 * @param infomark
	 * @return
	 * @throws QbGetDataException
	 */
	private String getMemberInfo(String method, int uid, int infomark)
			throws QbGetDataException {
		String url ="";
		String resultJson = null;
		try {
			Face173AccessLog accessLog = getAccessLog();
			accessLog.setCallService(this.getClass().getName());
	
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("method", memberURL);
			map.put("apikey", FaceContants.API_KEY);
			map.put("ver", FaceContants.API_VERSION);
			map.put("uid", uid);
			map.put("returnstyle", FaceContants.JSON_RETURN_STYLE);
			map.put("sessionkey", FaceContants.DEFAULT_SESSIONKEY);
			map.put("infomark", infomark);
			url = FaceStringUtil.createURLString(faceSNSURL, map);
	
			accessLog.setCallServiceParam(url);
			resultJson = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE).trim();
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			return resultJson;
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);

			logger.error("getMemberInfo throw QbGetDataException"+ e.getMessage(),e);
			throw new QbGetDataException("getMemberInfo throw Exception"+ e.getMessage(),e);
		}
	}

	private String isFocus(String method, int uid, String gamecode)
			throws QbGetDataException {
		String resultJson = null;
		String url="";
		try {
			Face173AccessLog accessLog = getAccessLog();
			accessLog.setCallService(this.getClass().getName());
	
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("method", method);
			map.put("apikey", FaceContants.API_KEY);
			map.put("ver", FaceContants.API_VERSION);
			map.put("uid", uid);
			map.put("gamecode", gamecode);
			map.put("gameCode", gamecode);
			map.put("returnstyle", FaceContants.JSON_RETURN_STYLE);
			map.put("sessionkey", FaceContants.DEFAULT_SESSIONKEY);
			url = FaceStringUtil.createURLString(faceSNSURL, map);
			accessLog.setCallServiceParam(url);
			resultJson = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE).trim();
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			return resultJson;
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GAME);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("isFocus throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("isFocus throw Exception"+ e.getMessage(),e);
		}
	}

	private String getInfoCompletion(String method, int uid, int infomark)
			throws QbGetDataException {

		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("method", infoCompletionURL);
		map.put("apikey", FaceContants.API_KEY);
		map.put("ver", FaceContants.API_VERSION);
		map.put("uid", uid);
		map.put("returnstyle", FaceContants.JSON_RETURN_STYLE);
		map.put("infomark", infomark);
		String url = FaceStringUtil.createURLString(faceSNSURL, map);
		accessLog.setCallServiceParam(url);
		String resultJson = null;
		try {
			resultJson = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultJson);
			return resultJson;
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_COMPLETION);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultJson);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getInfoCompletion throw Exception" + e.getMessage(),e);
			throw new QbGetDataException("getInfoCompletion throw Exception"+ e.getMessage(),e);
		}
	}

	private String getUserLv(String method, int uid, String passport)
			throws QbGetDataException {

		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userid", uid);
		String chk = MD5.encode(passport + "." + FaceContants.MD5_KEY);
		map.put("chk", chk);
		String url = FaceStringUtil.createURLString(facePHPURL + getJifen, map);
		accessLog.setCallServiceParam(url);
		String jsonURL = null;
		try {
			jsonURL = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(jsonURL);
			Document doc;
			Element flagEle = null;
			Element jifenEle = null;
			doc = DocumentHelper.parseText(jsonURL);
			Element root = doc.getRootElement();
			flagEle = root.element("flag");
			jifenEle = root.element("jifen");
			return "{\"flag\":\"" + flagEle.getData() + "\",\"jifen\":\""+ jifenEle.getData() + "\"}";
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_LV);
			outService.setObject("uid:" + uid);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(jsonURL);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("getUserLv throw Exception" + e.getMessage(),e);
			throw new QbGetDataException("getUserLv throw Exception"+ e.getMessage(),e);
		}
	}

	/**
	 * 回写修改用户基本信息接口实现
	 * 
	 * @see 暂时不调用
	 */
	@Override
	public boolean updateUserInfo(UserInfo userInfo, int uid, String passport)
			throws QbGetDataException {
		// Face173AccessLog accessLog = getAccessLog();
		// accessLog.setCallService(this.getClass().getName());
		// AddressInfo address = this.getAddressInfo(uid,passport);
		// Map<String,Object> map = new HashMap<String,Object>();
		// map.put("apikey", FaceContants.API_KEY);
		// map.put("method", "Member.updateMemberContact");
		// map.put("ver", FaceContants.API_VERSION);
		// map.put("uid", uid);
		// map.put("name", userInfo.getName());
		// map.put("sex", userInfo.getSex());
		// map.put("birthday", userInfo.getBirthday());
		// map.put("constellation", userInfo.getConstellation());
		// map.put("gamestage", userInfo.getPlayStage());
		//
		// String url = FaceStringUtil.createURLString(faceSNSURL + "/" +
		// memberURL,map);
		//
		// accessLog.setCallServiceParam(url);
		// String resultJson = null;
		// boolean flag = false;
		// try {
		// resultJson = FaceHttpUtil.doRequest(url, null,
		// null,FaceContants.DEFAULT_TRANS_ENCODE).trim();
		// } catch (QbGetDataException e) {
		// e.printStackTrace();
		//
		// OutService outService = new OutService();
		// outService.setService(url);
		// outService.setType(FaceContants.FAIL_GAME);
		// outService.setObject("uid:"+uid);
		// outService.setMethod(this.getClass().getName());
		// outService.setMemo(resultJson);
		// outServiceFailDAO.saveOutServiceFail(outService);
		//
		// logger.info("getMemberInfo throw QbGetDataException" +
		// e.getMessage());
		// throw new QbGetDataException("getMemberInfo throw Exception" +
		// e.getMessage());
		// }
		// ReplyInfoCheck rfc = JacksonUtil.toObject(resultJson,
		// ReplyInfoCheck.class);
		// if(rfc != null){
		// if(rfc.getCode()>0){
		// flag = true;
		// }
		// }
		// return flag;
		return false;
	}

	@Override
	public boolean updateContact(int uid, UserContact userContact,
			String passport) throws QbGetDataException {
		// Face173AccessLog accessLog = getAccessLog();
		// accessLog.setCallService(this.getClass().getName());
		// AddressInfo address = this.getAddressInfo(uid,passport);
		// Map<String,Object> map = new HashMap<String,Object>();
		// map.put("apikey", FaceContants.API_KEY);
		// map.put("method", "Member.updateMemberContact");
		// map.put("ver", FaceContants.API_VERSION);
		// map.put("uid", uid);
		// map.put("province",address.getProvince());
		// map.put("city",address.getCity());
		// map.put("address", address.getDetailedAddress());
		// map.put("email", userContact.getEmail());
		// map.put("phone", address.getMobilephone());
		// map.put("msn", userContact.getMSN());
		// map.put("qq", userContact.getQqNum());
		// String url = FaceStringUtil.createURLString(faceSNSURL + "/" +
		// memberURL,
		// map);
		//
		// accessLog.setCallServiceParam(url);
		// String resultJson = null;
		// boolean flag = false;
		// try {
		// resultJson = FaceHttpUtil.doRequest(url, null,
		// null,FaceContants.DEFAULT_TRANS_ENCODE).trim();
		// } catch (QbGetDataException e) {
		// e.printStackTrace();
		//
		// OutService outService = new OutService();
		// outService.setService(url);
		// outService.setType(FaceContants.FAIL_GAME);
		// outService.setObject("uid:"+uid);
		// outService.setMethod(this.getClass().getName());
		// outService.setMemo(resultJson);
		// outServiceFailDAO.saveOutServiceFail(outService);
		//
		// logger.info("getMemberInfo throw QbGetDataException" +
		// e.getMessage());
		// throw new QbGetDataException("getMemberInfo throw Exception" +
		// e.getMessage());
		//
		// }
		//
		// ReplyInfoCheck rfc = JacksonUtil.toObject(resultJson,
		// ReplyInfoCheck.class);
		// if(rfc != null){
		// if(rfc.getCode()>0){
		// flag = true;
		// }
		// }
		// return flag;
		return false;
	}
}